#include "clientwindow.h"
#include "ui_clientwindow.h"

//TODO: Ajouter un bouton pour libérer un fichier téléchargé
//TODO: Ajouter un teste au téléchargement pour vérifier que le fichier n'est pas déjà téléchargé
//TODO: Rendre le widjet centrale dockable
//TODO: Autoriser tout les widjet a être à gauche à droite ou au centre
//TODO: Ajouter un a propos de
//TODO: Ajouter un a propos de Qt
//TODO: Ajouter un menu de support multilingue
//TODO: Gérer le support multilingue
//TODO: Rendre les dock flotant et fermable
//TODO: Ajouter un menu de visibilité des docks

ClientWindow::ClientWindow(QWidget *parent) :
    PaneledMainWindow(parent),
    ui(new Ui::ClientWindow)
{
    ui->setupUi(this);
    connectionDialog = new ConnectionDialog(this);
    connection = new Connection(this);
    client = new Client(connection,this);
    this->connect(connectionDialog,SIGNAL(accepted()),SLOT(on_connectionDialog_accepted()));
    this->connect(connection,SIGNAL(lineReceived(QString)),SLOT(on_connection_receiveLine(QString)));
    this->connect(connection,SIGNAL(dataReceived(QByteArray)),SLOT(on_connection_receiveData(QByteArray)));
    this->connect(connection,SIGNAL(lineSended(QString)),SLOT(on_connection_sendLine(QString)));
    this->connect(connection,SIGNAL(dataSended(QByteArray)),SLOT(on_connection_sendData(QByteArray)));
    this->connect(connection,SIGNAL(dataReceiving(qreal)),SLOT(on_connection_receivingData(qreal)));
    ui->widget->setVisible(false);
}

ClientWindow::~ClientWindow()
{
    delete ui;
    disconnect();
}

void ClientWindow::on_actionQuitter_triggered()
{
    this->close();
}

void ClientWindow::on_actionSe_connecter_triggered()
{
    ui->actionSe_connecter->setEnabled(false);
    if(!connection->isConnected())
        connectionDialog->show();
    else
    {
        connection->disconnect();
        ui->actionSe_connecter->setText(tr("Connect"));
        ui->textEdit_Consol->clear();
        ui->listWidget_ServerFile->clear();
        ui->listWidget_ClientFile->clear();
        ui->dockWidget_Client->setEnabled(false);
        ui->dockWidget_Server->setEnabled(false);
        ui->dockWidget_Consol->setEnabled(false);
        ui->actionSe_connecter->setEnabled(true);
    }
}

void ClientWindow::on_toolButton_clicked()
{
    if(connection->isConnected())
    {
        QStringList* list = new QStringList();
        if(client->getList(*list))
        {
            ui->listWidget_ServerFile->clear();
            foreach (QString file, *list) {
                ui->listWidget_ServerFile->addItem(new QListWidgetItem(file));
            }
        }
        delete list;
    }
}

void ClientWindow::on_toolButton_2_clicked()
{
    if(connection->isConnected())
    {
        if(ui->listWidget_ServerFile->selectedItems().count() > 0)
        {
            QString file = ui->listWidget_ServerFile->selectedItems().at(0)->text();
            Client::FileState fileState;
            if(client->getFile(file,"./" + file,fileState))
            {
                if(fileState == Client::Exist)
                    QMessageBox::information(this,tr("Download"),tr("Download success"));
                else if(fileState == Client::Busy)
                    QMessageBox::information(this,tr("Download"),tr("File is busy"));
                else if(fileState == Client::NotExist)
                    QMessageBox::information(this,tr("Download"),tr("File doesn't exist"));
            }
        }
        else
        {
            QMessageBox::warning(this,tr("Download"),tr("Please select a file to download"));
        }
    }
}

void ClientWindow::on_connectionDialog_accepted()
{
    if(connection->connect(connectionDialog->address(),
                           connectionDialog->port()))
    {
        ui->actionSe_connecter->setText(tr("Disconnect"));
        ui->dockWidget_Client->setEnabled(true);
        ui->dockWidget_Server->setEnabled(true);
        ui->dockWidget_Consol->setEnabled(true);
    }
    else
        QMessageBox::warning(this,tr("Connection fail"),tr("The connection have fail"));
    ui->actionSe_connecter->setEnabled(true);
}

void ClientWindow::on_connection_receiveLine(const QString line)
{
    appendLine(tr("RECEPTION : %1").arg(line), QColor(Qt::blue));
}

void ClientWindow::on_connection_receiveData(const QByteArray data)
{
    appendLine(tr("RECEPTION : %1  bytes recepted.").arg(data.size()), QColor(Qt::darkCyan) );
}

void ClientWindow::on_connection_sendLine(const QString line)
{
    appendLine(tr("EMISSION : %1").arg(line), QColor(Qt::darkGreen));
}

void ClientWindow::on_connection_sendData(const QByteArray data)
{
    appendLine(tr("EMISSION : %1  bytes emited.").arg(data.size()), QColor(Qt::darkGreen));
}

void ClientWindow::on_connection_receivingData(const qreal progress)
{
    qint32 _progress = (qint32) (progress * 100);
    if((_progress % 2) == 0)
    {
        if(!ui->widget->isVisible())
            ui->widget->setVisible(true);
        QCoreApplication::processEvents();
        ui->progressBar->setValue(_progress);
        ui->statusBar->showMessage(tr("Download progress (%1%)").arg(_progress),3000);
        if(_progress == 100)
        {
            ui->widget->setVisible(false);
        }
    }
}

void ClientWindow::appendLine(const QString line, const QColor color)
{
    ui->textEdit_Consol->setTextColor(color);
    ui->textEdit_Consol->append(line);
    ui->textEdit_Consol->setTextColor(QColor(Qt::black));
    ui->textEdit_Consol->scrollToAnchor("\0");
    ui->statusBar->showMessage(line.simplified(),3000);
}

